package com.baseframe.sys.service.impl;


import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baseframe.common.annotation.DataFilter;
import com.baseframe.common.utils.PageUtils;
import com.baseframe.sys.entity.AppClass;
import com.baseframe.sys.entity.AppInfo;
import com.baseframe.sys.entity.FrameOu;
import com.baseframe.sys.service.IAppInfoService;
import com.baseframe.sys.service.dao.AppClassRepository;
import com.baseframe.sys.service.dao.AppInfoRepository;

/**
 * @author mzl
 */
@Service("appinfoService")
public class AppInfoServiceImpl implements IAppInfoService {


    @Autowired
    private AppInfoRepository dao;
    @Autowired
    private AppClassRepository cdao;
    @PersistenceContext
    private EntityManager em;


	@Override
	@DataFilter(subDept = true, user = false)
	public PageUtils queryPage(Map<String, Object> params) {
		String appname = (String)params.get("appname");
		int pageSize = Integer.parseInt((String)params.get("limit"));
		int page = Integer.parseInt((String)params.get("page"));
		String sidx = (String)params.get("sidx");
		String order = (String)params.get("order");
		String chql="select count(1) from AppInfo t where 1=1";
		String hql="from AppInfo t where 1=1";
		if(appname!=null&&!appname.trim().equals("")){
			chql+=" and t.appname like '%"+appname+"%'";
			hql+=" and t.appname like '%"+appname+"%'";
		}
		if(sidx!=null&&!sidx.equals("")){
			hql+=" order by t."+sidx+" "+order;
		}
		int total = Integer.parseInt(em.createQuery(chql).getSingleResult().toString());
		List<AppInfo> infolist= em.createQuery(hql).setFirstResult((page-1)*pageSize).setMaxResults(page*pageSize).getResultList();
		//classname取值
		List<AppClass> clist=cdao.findAll();
		infolist.forEach(info -> {
            Optional<AppClass> ouOptional = clist.stream()
                    .filter(temp -> temp.getId()==info.getAppclass())
                    .findFirst();
            if (ouOptional.isPresent()) {
            	info.setAppclassName(ouOptional.get().getClassname());
            } else {
            }
        });
		PageUtils p =  new PageUtils(infolist, total, pageSize, page);
		return p;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(AppInfo info) {
		info.setCreateTime(new Date());
		dao.save(info);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(AppInfo info) {
		info.setUpdateTime(new Date());
		dao.save(info);
	}


	@Override
	public AppInfo selectById(int id) {
		// TODO Auto-generated method stub
		return dao.findOne(id);
	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub
		dao.delete(id);
	}


	
}
